package com.moxi.mogublog.admin.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.moxi.mogublog.utils.ServletUtil;
import com.moxi.mougblog.base.global.BaseSysConf;
import com.moxi.mougblog.base.global.ECode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 认证进入点 (认证失败处理类 返回未授权)
 *
 * @author LiShuai
 * @date 2020/5/27 10:08
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException) throws IOException {

        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        Map<String, Object> result = new HashMap<>(BaseSysConf.NUM_THREE);
        result.put("code", ECode.UNAUTHORIZED);
        result.put("msg", msg);
        result.put("data", "token无效或过期");
        ServletUtil.renderString(response, JSON.toJSONString(result));
    }

}
